import { Component, Input, OnInit, Inject, forwardRef } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { ComItem } from '../../route/entry/com-item';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { OpenMemberInvitationModalComponent } from '../open-member-invitation-modal/open-member-invitation-modal.component';


@Component({
  selector: 'app-button-nav-default',
  templateUrl: './button-nav-default.component.html',
  styleUrls: ['./button-nav-default.component.scss'],
})
export class ButtonNavDefaultComponent implements OnInit {
  subComs: ComItem[] = [];
  @Input() tagData: any;
  aWidth: string;
  isSelected: boolean;
  currentClickObj: any;
  currentCLickIndexTab: any;
  isRootURL: any; // 用于检查URL是否有变化
  receiverTag = 'ButtonNavDefaultComponentReceiver';
  constructor(
    private eventService: EventService,
    private httpService: HttpService,
    private loadingCtrl: LoadingController
  ) {
    if (this.eventService.eventEmit.listenerCount(this.receiverTag) > 0) {
      this.eventService.eventEmit.removeListener(this.receiverTag);
    }
    this.eventService.eventEmit.on(this.receiverTag, res => {
      if (localStorage.getItem(this.receiverTag + 'Tag')) {
        localStorage.removeItem(this.receiverTag + 'Tag');
        this.subComs.push(res);
      }
    });
  }

  ngOnInit() {
    this.aWidth = 100 / this.tagData.data.length + '%';
    const cDataObj = this.tagData.currentData;
    if (cDataObj !== undefined) {
      const tags = cDataObj.tags;
      if (tags !== undefined && tags.length > 0) {
        const len = tags.length;
        for (let i = 0; i < len; i++) {
          const tag = tags[i];
          // #task-view-916
          if (this.tagData.refresh) {
            tag.isPullToRefresh = this.tagData.refresh;
          }
          const eventEmitObj = { style: tag.style, tag, receiverTag: this.receiverTag };
          localStorage.setItem('generatedComItemTag', JSON.stringify(eventEmitObj));
          this.eventService.eventEmit.emit('generatedComItem', '');
          // this.tabService.getComsDataByStyle(tag.style, callData => {
          //   if (callData) {
          //     this.subComs.push(callData);
          //   }
          // }, tag);

        }
      }
    }
    // this.reloadCurrentTab();

  }
  change(obj, indexTab) {
    if (obj !== undefined && obj.partLink !== undefined) {
      this.tagData.currentTab = indexTab;
      setTimeout(async () => {
        const loading = await this.loadingCtrl.create({
          message: '',
          cssClass: 'my-custom-loadingCtrl',
          spinner: null,
          duration: 350,
          showBackdrop: false,
          // backdropDismiss: false
        });
        await loading.present();
        // todo 如果params里面带经纬度则传经纬度
        this.httpService.post('application/part',
          {
            viewId: obj.partLink.target,
            sessionId: localStorage.getItem("sessionId"),
            params: obj.partLink.params
          }, (res: any) => {
            if (res !== undefined && res != null) {
              setTimeout(() => {
                let footerTag = {};
                try {
                  if (res.script.includes('"style":"tag.PhoneTagLogic","name":null,"linearLayout":"footer"')) {
                    const pageData = JSON.parse(res.script);
                    footerTag = pageData.tags.pop();
                    res.script = JSON.stringify(pageData);
                  }
                } catch (error) {
                  console.log('error----->' + JSON.stringify(error));
                }
                // 通知NavOne 更新footer TODO 有bug 会更新所有nav-one
                // localStorage.setItem("nav1UpdateFooterComsTag", '1');
                // this.eventService.eventEmit.emit('nav1UpdateFooterComs', this.getResObj(footerTag));

                this.tagData.currentData = JSON.parse(res.script);
                // localStorage.setItem("needRefresh","true");
                this.tagData.currentData.isPart = false;
                localStorage.setItem("dataMapSubContainer", JSON.stringify(this.tagData));
                this.eventService.eventEmit.emit('refreshSubTabContainer', 'refreshSubTabContainer');
              }, 0);

            }
          });
      }, 0);
    }
  }
  reloadCurrentTab() {
    this.eventService.eventEmit.on('refreshbtNavDefaultTab', data => {
      console.log('btNavDefaultTab------->');
      document.getElementById('btNavDefaultTab' + this.tagData.currentTab).click();
    });
  }


  getResObj(footerTag) {
    const res = { script: '' };
    if (footerTag) {
      const pageData = {
        type: "page",
        style: "page.DefaultPageLogic",
        name: null,
        titleBar: {},
        disableBack: false,
        menus: {},
        views: [
          {
            type: "view",
            style: "view.DefaultViewLogic",
            name: null,
            tags: [footerTag]
          }
        ]
      };
      res.script = JSON.stringify(pageData);
    }
    return res;
  }
}
